﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace KingCat_Socket
{
    public class ConnectServerSocket
    {
        //网络变量
        private IPAddress IPAddr_Srv;
        private TcpClient myclient;
        private int Port_Srv;
        private StreamReader streamreader;
        private StreamWriter streamwriter;
        private NetworkStream netwkstream;
        private static ConnectServerSocket scs;
        private IPEndPoint ipendp;

        private ConnectServerSocket()
        {

        }

        public static ConnectServerSocket getInstance()
        {
          if (scs == null)
          {
               scs = new ConnectServerSocket();
          }
      
            return scs;
        }


        /// <summary>
        /// 客户端连接服务器
        /// </summary>
        /// <param name="serverIp">服务器ip</param>
        /// <param name="serverPort">服务器端口号</param>
        public void SetConnectInfo(String serverIp, String serverPort)
        {
            
            try
            {
                IPAddr_Srv = IPAddress.Parse(serverIp);
                Port_Srv = Convert.ToInt32(serverPort);
                ipendp = new IPEndPoint(IPAddr_Srv, Port_Srv);
                myclient = new TcpClient();
                myclient.Connect(ipendp);
                netwkstream = myclient.GetStream();
                streamreader = new StreamReader(netwkstream);
                streamwriter = new StreamWriter(netwkstream);
            }
            catch (Exception e3)
            {
               throw  new Exception();
            }
          
        }

        private object Exception()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public StreamReader getStreamReader()
        {
            return streamreader;
        }

        public StreamWriter getStreamWriter()
        {
            return streamwriter;
        }

        public NetworkStream getNetWorkStream()
        {
            return netwkstream;
        }

        public TcpClient getTcpClient()
        {
            return myclient;
        }

        public IPEndPoint getServerIpAndPort()
        {
            return ipendp;
        }

        public void closeStream()
        {
            if (streamreader != null)
            { streamreader.Close(); }
            if (streamwriter != null)
            { streamwriter.Close(); }
            if (netwkstream != null)
            { netwkstream.Close(); }
            if (myclient != null)
            { myclient.Close(); }
        }
    }
}
